<template>
  <div class="visitor-sheet-list">
    <!-- 页面标题 -->
    <el-card
      class="header-card"
      shadow="never"
    >
      <div class="header-row">
        <h2>访客单管理</h2>
        <div class="header-actions">
          <el-button
            type="primary"
            :icon="Plus"
            @click="handleAdd"
          >
            新建访客单
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 智能导入提示 -->
    <el-alert
      type="success"
      :closable="true"
      show-icon
      style="margin-top: 16px"
    >
      <template #title>
        <span style="font-size: 14px">💡 想快速批量创建访客单？前往 <router-link to="/smart-import" style="font-weight: bold; color: #67c23a; text-decoration: underline;">智能导入</router-link> 页面，粘贴客户信息即可 AI 智能解析！</span>
      </template>
    </el-alert>

    <!-- 统计卡片 -->
    <el-row
      :gutter="16"
      style="margin-top: 16px"
    >
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="总访客单数"
            :value="visitorSheetStore.total"
          />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="高意向客户"
            :value="visitorSheetStore.highIntentionSheets.length"
          />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="平均满意度"
            :value="visitorSheetStore.averageSatisfaction"
            suffix="分"
          />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card
          shadow="hover"
          class="stat-card"
        >
          <el-statistic
            title="本月带看"
            :value="monthlyVisits"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 筛选区域 -->
    <el-card
      shadow="never"
      style="margin-top: 16px"
    >
      <el-form
        :model="queryParams"
        inline
      >
        <el-form-item label="日期范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 260px"
            @change="handleDateChange"
          />
        </el-form-item>

        <el-form-item label="意向度">
          <el-select
            v-model="queryParams.intention"
            placeholder="请选择意向度"
            clearable
            style="width: 150px"
          >
            <el-option
              label="高"
              value="high"
            />
            <el-option
              label="中"
              value="medium"
            />
            <el-option
              label="低"
              value="low"
            />
            <el-option
              label="无"
              value="none"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="客户ID">
          <el-input-number
            v-model="queryParams.lead_id"
            :min="1"
            placeholder="客户ID"
            controls-position="right"
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item label="房源ID">
          <el-input-number
            v-model="queryParams.property_id"
            :min="1"
            placeholder="房源ID"
            controls-position="right"
            style="width: 150px"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :icon="Search"
            @click="handleSearch"
          >
            查询
          </el-button>
          <el-button
            :icon="Refresh"
            @click="handleReset"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card
      shadow="never"
      style="margin-top: 16px"
    >
      <el-table
        v-loading="visitorSheetStore.loading"
        :data="visitorSheetStore.visitorSheets"
        stripe
        border
      >
        <el-table-column
          prop="id"
          label="ID"
          width="80"
        />

        <el-table-column
          prop="lead_id"
          label="客户ID"
          width="100"
        />

        <el-table-column
          prop="property_id"
          label="房源ID"
          width="100"
        />

        <el-table-column
          prop="visit_date"
          label="带看日期"
          width="120"
        >
          <template #default="{ row }">
            {{ formatDate(row.visit_date) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="visit_time"
          label="带看时间"
          width="100"
        />

        <el-table-column
          prop="duration_minutes"
          label="时长(分钟)"
          width="110"
        />

        <el-table-column
          prop="satisfaction"
          label="满意度"
          width="100"
        >
          <template #default="{ row }">
            <el-rate
              v-if="row.satisfaction"
              :model-value="row.satisfaction"
              disabled
              show-score
              text-color="#ff9900"
            />
            <span
              v-else
              style="color: #999"
            >未评</span>
          </template>
        </el-table-column>

        <el-table-column
          prop="intention"
          label="意向度"
          width="100"
        >
          <template #default="{ row }">
            <el-tag :type="getIntentionType(row.intention)">
              {{ getIntentionText(row.intention) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          prop="pros_tags"
          label="优点标签"
          min-width="150"
          show-overflow-tooltip
        />

        <el-table-column
          prop="cons_tags"
          label="缺点标签"
          min-width="150"
          show-overflow-tooltip
        />

        <el-table-column
          prop="notes"
          label="备注"
          min-width="150"
          show-overflow-tooltip
        />

        <el-table-column
          label="操作"
          width="180"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :total="visitorSheetStore.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSearch"
          @current-change="handleSearch"
        />
      </div>
    </el-card>

    <!-- 传统模式：新建/编辑对话框 -->
    <VisitorSheetDialog
      v-model="dialogVisible"
      :visitor-sheet-data="currentVisitorSheet"
      @success="handleDialogSuccess"
    />

    <!-- 详情抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="访客单详情"
      size="600px"
      direction="rtl"
    >
      <div
        v-if="detailData"
        class="detail-content"
      >
        <el-descriptions
          :column="1"
          border
        >
          <el-descriptions-item label="访客单ID">
            {{ detailData.id }}
          </el-descriptions-item>
          <el-descriptions-item label="客户信息">
            {{ detailData.lead_name || '-' }} ({{ detailData.lead_phone || '-' }})
          </el-descriptions-item>
          <el-descriptions-item label="房源地址">
            {{ detailData.property_address || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="经纪人">
            {{ detailData.agent_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="带看日期">
            {{ formatDate(detailData.visit_date) }}
          </el-descriptions-item>
          <el-descriptions-item label="带看时间">
            {{ detailData.visit_time || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="停留时长">
            {{ detailData.duration_minutes || '-' }} 分钟
          </el-descriptions-item>
          <el-descriptions-item label="满意度">
            <el-rate
              v-if="detailData.satisfaction"
              :model-value="detailData.satisfaction"
              disabled
              show-score
            />
            <span v-else>未评</span>
          </el-descriptions-item>
          <el-descriptions-item label="意向度">
            <el-tag :type="getIntentionType(detailData.intention)">
              {{ getIntentionText(detailData.intention) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="优点标签">
            {{ detailData.pros_tags || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="缺点标签">
            {{ detailData.cons_tags || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ detailData.notes || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(detailData.created_at) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(detailData.updated_at) }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
/**
 * 访客单列表页面
 * 完整实现版本
 */
import { ref, reactive, computed, onMounted } from 'vue'
import { useVisitorSheetStore } from '@/stores/visitor-sheet'
import notify from '@/utils/notify'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import VisitorSheetDialog from './VisitorSheetDialog.vue'
import type { VisitorSheet, VisitorSheetWithDetails } from '@/api/types'
import dayjs from 'dayjs'

// ========== Store ==========
const visitorSheetStore = useVisitorSheetStore()

// ========== 响应式数据 ==========
const queryParams = reactive({
  page: 1,
  page_size: 20,
  lead_id: undefined as number | undefined,
  property_id: undefined as number | undefined,
  agent_id: undefined as number | undefined,
  start_date: undefined as string | undefined,
  end_date: undefined as string | undefined,
  intention: '',
})

const dateRange = ref<[string, string] | null>(null)
const dialogVisible = ref(false)
const drawerVisible = ref(false)
const currentVisitorSheet = ref<VisitorSheet | null>(null)
const detailData = ref<VisitorSheetWithDetails | null>(null)

// ========== 计算属性 ==========
const monthlyVisits = computed(() => {
  const now = dayjs()
  return visitorSheetStore.visitorSheets.filter((vs: VisitorSheet) => {
    const visitDate = dayjs(vs.visit_date)
    return visitDate.month() === now.month() && visitDate.year() === now.year()
  }).length
})

// ========== 方法 ==========

/**
 * 日期范围变化
 */
const handleDateChange = (dates: [string, string] | null) => {
  if (dates) {
    queryParams.start_date = dates[0]
    queryParams.end_date = dates[1]
  } else {
    queryParams.start_date = undefined
    queryParams.end_date = undefined
  }
}

/**
 * 查询列表
 */
const handleSearch = () => {
  visitorSheetStore.fetchVisitorSheets(queryParams)
}

/**
 * 重置筛选
 */
const handleReset = () => {
  Object.assign(queryParams, {
    page: 1,
    page_size: 20,
    lead_id: undefined,
    property_id: undefined,
    agent_id: undefined,
    start_date: undefined,
    end_date: undefined,
    intention: '',
  })
  dateRange.value = null
  handleSearch()
}

/**
 * 新建访客单（传统模式）
 */
const handleAdd = () => {
  currentVisitorSheet.value = null
  dialogVisible.value = true
}

/**
 * 查看详情
 */
const handleView = async (row: VisitorSheet) => {
  await visitorSheetStore.fetchVisitorSheet(row.id)
  detailData.value = visitorSheetStore.currentVisitorSheet
  drawerVisible.value = true
}

/**
 * 编辑访客单
 */
const handleEdit = (row: VisitorSheet) => {
  currentVisitorSheet.value = row
  dialogVisible.value = true
}

/**
 * 删除访客单
 */
const handleDelete = (row: VisitorSheet) => {
  notify.confirm(`确定要删除访客单【ID: ${row.id}】吗？`, '提示').then(async () => {
    const success = await visitorSheetStore.deleteVisitorSheet(row.id)
    if (success) {
      handleSearch()
    }
  })
}

/**
 * 对话框成功回调
 */
const handleDialogSuccess = () => {
  dialogVisible.value = false
  handleSearch()
}

/**
 * 获取意向度标签类型
 */
const getIntentionType = (intention?: string): 'danger' | 'warning' | 'info' | undefined => {
  const typeMap: Record<string, 'danger' | 'warning' | 'info'> = {
    high: 'danger',
    medium: 'warning',
    low: 'info',
  }
  return intention ? typeMap[intention] : undefined
}

/**
 * 获取意向度文本
 */
const getIntentionText = (intention?: string) => {
  const textMap: Record<string, string> = {
    high: '高',
    medium: '中',
    low: '低',
    none: '无',
  }
  const key = intention ?? 'none'
  return textMap[key] || key
}

/**
 * 格式化日期
 */
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD')
}

/**
 * 格式化日期时间
 */
const formatDateTime = (datetime: string) => {
  return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss')
}

// ========== 生命周期 ==========
onMounted(() => {
  handleSearch()
})
</script>

<style scoped>
.visitor-sheet-list {
  padding: 0;
}

.header-card {
  margin-bottom: 0;
}

.header-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-row h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stat-card {
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

.detail-content {
  padding: 16px 0;
}
</style>
